const fs = require("fs");
const path = require("path");
const crypto = require("crypto");
const NodeRSA = require("node-rsa");
let key = NodeRSA({ b: 1024 });
key.setOptions({ encryptionScheme: "pkcs1" });
//创建公钥和私钥
function generateKey() {
  const PUBLIC_KEY = key.exportKey("pkcs8-public-pem");
  const PRIVATE_KEY = key.exportKey("pkcs8-private-pem");
  fs.writeFile(
    path.resolve(__dirname, "../cert/public.pem"),
    PUBLIC_KEY,
    (err) => {
      if (!err) {
        console.log("公钥写入成功");
      }
    }
  );
  fs.writeFile(
    path.resolve(__dirname, "../cert/private.key"),
    PRIVATE_KEY,
    (err) => {
      if (!err) {
        console.log("私钥写入成功");
      }
    }
  );
}
function getPublicKey() {
  return fs
    .readFileSync(path.resolve(__dirname, "../cert/public.pem"))
    .toString("utf-8");
}
function decryptCode(data) {
  key.importKey(
    fs.readFileSync(path.resolve(__dirname, "../cert/private.key"))
  ); //导入私钥
  return key.decrypt(data, "utf8");
}
const md5 = (content) => {
  let md5 = crypto.createHash("md5");
  return md5.update(Buffer.from(content)).digest("hex");
};
module.exports = { md5, getPublicKey, decryptCode, generateKey };
